# 设置目标Linux/aarch64(系统/处理器)
set(CMAKE_SYSTEM_NAME    Linux)
set(CMAKE_SYSTEM_PROCESSOR aarch64)

# 设置编译选项（警告、安装加固RELRO/PIE、调试符号-g和优化-O2）
# set(CMAKE_FLAGS_PUBLIC "-Wall -Werror -Wformat -wfloat-equal -Wtrampolines -g -O2 -rdynamic -W1,-z,noexecstack,-z,relro,-z,now -fno-strict-aliasing -fstack-protector-strong -D_FORTIFY_SOURCE=2 -fPIE -pie -fPIC"）

# 架构
set(CMAKE_FLAGS_ARM64 " -march=armv8-a+crc")

# 交叉编译器前缀所在目录（根据实际安装路径修改/usr/bin）
set(TOOLCHAIN_ROOT       /usr/bin)
set(CROSS_COMPILE aarch64-linux-gnu-)
set(CMAKE_C_COMPILER     ${TOOLCHAIN_ROOT}/${CROSS_COMPILE}gcc)
set(CMAKE_ASM_COMPILER   ${TOOLCHAIN_ROOT}/${CROSS_COMPILE}gcc)
set(CMAKE_CXX_COMPILER   ${TOOLCHAIN_ROOT}/${CROSS_COMPILE}g++)

# 如果有独立的sysroot，取消下面注释并调整路径(./arm64/sysroot)
set(ENV{SYSROOT_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/arm64/sysroot")
message(STATUS "SYSROOT_PATH目录是: $ENV{SYSROOT_PATH}")

if(NOT DEFINED ENV{SYSROOT_PATH})
  message(FATAL_ERROR "环境变量 SYSROOT_PATH 未设置！")
  set(CMAKE_SYSROOT arm64/sysroot)
else()
  message(STATUS "使用环境变量 SYSROOT_PATH: $ENV{SYSROOT_PATH}")
  # 将环境变量注入 CMAKE_SYSROOT
  set(CMAKE_SYSROOT $ENV{SYSROOT_PATH})
  # set(CMAKE_SYSROOT    $ENV{SYSROOT_PATH} CACHE PATH "Cross-compile sysroot")
endif()

# 搜索根路径（用于查找库和头文件）
set(CMAKE_FIND_ROOT_PATH  ${CMAKE_SYSROOT}  ${CMAKE_SYSROOT}/3rd)

# 控制查找规则：在主机上查程序，在目标根路径查库、头文件、包（限制CMake查找路径只在sysroot中）
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM  NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY  ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE  ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE  ONLY)

# 默认编译选项：针对ARMv8-A架构，必要时可添加-mcpu -mtune
set(CMAKE_C_FLAGS         "-march=armv8-a"    CACHE STRING "" FORCE)
set(CMAKE_CXX_FLAGS       "-march=armv8-a"    CACHE STRING "" FORCE)
# set(CMAKE_C_FLAGS         "$CMAKE_FLAGS_PUBLIC $CMAKE_FLAGS_ARM64")
# set(CMAKE_CXX_FLAGS         "$CMAKE_FLAGS_PUBLIC $CMAKE_FLAGS_ARM64 -std=c++11")

# 可选：如果需要链接标准C++库，确保以下行未被注释
# set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} --sysroot=${CMAKE_SYSROOT}")